//
//  CYCycleScroll.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/12.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYCycleScroll.h"
#import "CYCycleCell.h"
#import "CYDataSourceDelegate.h"
@interface CYCycleScroll ()<UICollectionViewDelegate,UICollectionViewDataSource>{
    UICollectionView *_collectionView;
    NSMutableArray *_titles;
    UIPageControl *_pageControl;
    NSUInteger currentindex ;
}
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation CYCycleScroll

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self buildUI];
        currentindex = 0;
    }
    return self;
}

-(void)buildUI{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(self.bounds.size.width, self.bounds.size.height);
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.pagingEnabled = true;
    _collectionView.backgroundColor = [UIColor clearColor];
    [_collectionView registerClass:[CYCycleCell class] forCellWithReuseIdentifier:@"CYCycleCell"];
    _collectionView.showsHorizontalScrollIndicator = false;
    [self addSubview:_collectionView];
    
    CGFloat controlHeight = 35.0f;
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - controlHeight, self.bounds.size.width, controlHeight)];
    _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    _pageControl.currentPageIndicatorTintColor = TEXT_GRAY_COLOR;
    [self addSubview:_pageControl];
    
}
- (NSTimer *)timer{
    if (!_timer)
        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
    return _timer;
}

- (void)updateTime{
    CGFloat offSetX = _collectionView.contentOffset.x;//获取当前滚动视图的contentOffSet的x值
    offSetX += _collectionView.bounds.size.width;//让scrollView向右滚动一个屏幕宽的距离
    [_collectionView setContentOffset:CGPointMake(offSetX, 0) animated:YES];//开始偏移并伴有动画效果
}
#pragma mark -
#pragma mark CollectionViewDelegate&DataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _titles.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString* cellId = @"CYCycleCell";
    CYCycleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    WS(self)
    cell.bounds = weakSelf.bounds;
    cell.imageName = _titles[indexPath.row];
    return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger page = scrollView.contentOffset.x/scrollView.bounds.size.width;
    if (page == 0) {//滚动到最左边
        [scrollView setContentOffset:CGPointMake(scrollView.bounds.size.width * (_titles.count - 2), 0) animated:NO];
        return;
    }else if (page == _titles.count - 1){//滚动到最右边
        [scrollView setContentOffset:CGPointMake(scrollView.bounds.size.width, 0) animated:NO];
        return;
    }
    _pageControl.currentPage = page - 1;
}

//拖拽scrollview的时候，暂停定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.timer invalidate];//取消计时器
    self.timer = nil;
    
}
//拖拽完成，减速过程完成，重启定时器
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t) 1.0 *NSEC_PER_SEC);
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        if (!_timer)
            [self.timer setFireDate:[NSDate distantPast]];
    });
    
}

#pragma mark -
#pragma mark Setter

-(void)setImageNames:(NSArray *)imageNames{
    if (!imageNames)
        return;
    else if (imageNames.count < 1)
        return;
    _titles = [NSMutableArray arrayWithArray:imageNames];
    [_titles addObject:imageNames.firstObject];
    [_titles insertObject:imageNames.lastObject atIndex:0];
    //    [_collectionView setContentOffset:CGPointMake(_collectionView.bounds.size.width, 0)];
    _pageControl.numberOfPages = imageNames.count;
    [self.timer setFireDate:[NSDate distantPast]];//开始
}

@end
